package com.cqut.hfh.ordering.controller;

import com.cqut.hfh.ordering.service.IFodPicService;
import com.cqut.hfh.ordering.utils.Message;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author LJH
 * @date 2019/6/26-10:51
 */
@Controller
@RequestMapping("/upload")
public class UploadPicController {


    @Resource
    private IFodPicService fodPicService;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String temp = handleFormUploadByByte(file, request);
        if ( temp != null){
            //成功
//            temp = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
//                    + request.getContextPath() + "/" + temp;
            temp = "upload" + temp;
            return Message.getReturnMsg(0, temp);
        }
        return Message.getReturnMsg(1, "上传失败");
    }


    /***
     * 利用字节方式写入文件
     * @param file
     * @return
     */
    private String handleFormUploadByByte( MultipartFile file, HttpServletRequest request) {
        //可利用nio对接收到的bytes做持久化操作
        if (!file.isEmpty()) {
            try {
                String path = request.getServletContext().getRealPath("upload");
                String temp = "/" + System.currentTimeMillis() + file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                FileUtils.writeByteArrayToFile(new File(path + temp), bytes);

                return temp;

            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

        }
        return null;
    }
}
